﻿using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceModel.Description;
using Justin.Wcf.Services;

namespace WindowsServiceHost
{
    public partial class Service : ServiceBase
    {
        public ServiceHost serviceHost = null;

        public Service()
        {
            InitializeComponent();
            ServiceName = "WCFWindowsServiceSample";
        }

        protected override void OnStart(string[] args)
        {
            //if (serviceHost != null)
            //{
            //    serviceHost.Close();
            //}

            //serviceHost = new ServiceHost(typeof(Justin.Wcf.Services.CalculatorService));
            //serviceHost.Open();

            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            Uri httpBaseAddress = new Uri("http://localhost:8000/");
            Uri tcpBaseAddress = new Uri("net.tcp://localhost:8001/");

            serviceHost = new ServiceHost(typeof(Justin.Wcf.Services.CalculatorService), httpBaseAddress, tcpBaseAddress);
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(behavior);

            serviceHost.AddServiceEndpoint(typeof(Justin.Wcf.Services.ICalculator), new WSHttpBinding(), "");
            serviceHost.AddServiceEndpoint(typeof(Justin.Wcf.Services.ICalculator), new NetTcpBinding(), "");

            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

            serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}
